var express = require('express')
var router = express.Router()
const Ballot = require('../models/ballot')
const Option = require('../models/option')
const Vote = require('../models/vote')
const User = require('../models/user')
const Op = require('sequelize').Op
const Tool = require('../libs/tool')
const { check, validationResult } = require('express-validator/check')
const Interceptor = require('../libs/interceptor')
var moment = require('moment')
const jwt = require('jsonwebtoken')
const config = require('../config/config')

router.get('/votes', async function(req, res, next) {
  let user = req.decoded
  if (!user) {
    return res.status(404).json({
      code: 404,
      msg: '未找到用户'
    })
  }
  let whereObj = {}
  if (req.query.title) {
    whereObj['voteName'] = {
      [Op.like]: '%' + req.query.title + '%'
    }
  }
  // whereObj['status'] = 1
  let orderObj = []
  if (req.query.order && req.query.sortby) {
    orderObj.push([req.query.sortby, req.query.order])
  } else {
    orderObj.push(['updated_at', 'desc'])
  }
  let interceptor = new Interceptor(req)
  let { offset = 1, limit = 10 } = interceptor.page()
  let result = await Vote.findAndCountAll({
    raw: true,
    where: whereObj,
    order: orderObj,
    offset: offset,
    limit: limit
  })
  for (let i = 0; i < result.rows.length; i++) {
    let ballot = await Ballot.findOne({
      include: [
        {
          attributes: [['vote_id', 'voteId']],
          association: Ballot.belongsTo(Option, { foreignKey: 'optionId' })
        }
      ],
      raw: true,
      where: { '$option.vote_id$': result.rows[i].voteId, userId: user.userId }
    })
    if (ballot) {
      result.rows[i]['voted'] = true
    } else {
      result.rows[i]['voted'] = false
    }
  }
  return res.json({
    code: 0,
    msg: '',
    items: result.rows,
    total: result.count
  })
})

router.get('/votes/:voteId(\\d+)/options', async function(req, res, next) {
  let whereObj = {}
  whereObj['status'] = 1
  whereObj['voteId'] = req.params.voteId
  let result = await Option.findAll({
    raw: true,
    where: whereObj
  })
  for (let i = 0; i < result.length; i++) {
    result[i]['checked'] = false
  }
  return res.json({
    code: 0,
    msg: '',
    items: result,
    total: result.count
  })
})

router.post(
  '/options/:optionId(\\d+)/check',
  [check('optionId').not().isEmpty().withMessage('选项ID不能为空')],
  async function(req, res) {
    let user = req.decoded
    if (!user) {
      return res.status(404).json({
        code: 404,
        msg: '未找到用户'
      })
    }
    let option = await Option.findOne({
      raw: true,
      where: { optionId: req.params.optionId }
    })
    if (!option) {
      return res.status(404).json({
        code: 404,
        msg: '未找到选项'
      })
    }
    let ballot = await Ballot.findOne({
      include: [
        {
          attributes: [['vote_id', 'voteId']],
          association: Ballot.belongsTo(Option, { foreignKey: 'optionId' })
        }
      ],
      raw: true,
      where: { '$option.vote_id$': option.voteId, userId: user.userId }
    })
    if (ballot) {
      return res.status(401).json({
        code: 401,
        msg: '您已经投过票了'
      })
    }
    let dbData = {
      status: 1,
      optionId: option.optionId,
      userId: user.userId,
      description: req.body.description,
      createdAt: Date.now(),
      updatedAt: Date.now()
    }
    let ballotDb = await Ballot.create(dbData)
    return res.json({
      code: 0,
      msg: '',
      ballot: ballotDb
    })
  }
)
let loginValidator = [
  check('loginName').not().isEmpty().withMessage('用户登录名不能为空'),
  check('passwd').not().isEmpty().withMessage('用户登录密码不能为空')
]
// 用户授权路径，返回JWT 的 Token 验证用户名密码
router.post('/login', loginValidator, async function(req, res) {
  const errors = validationResult(req)
  if (!errors.isEmpty()) {
    let errObj = Tool.validatorError(errors)
    return res.status(errObj.code).json(errObj)
  }
  let user = await User.findOne({
    where: {
      loginName: req.body.loginName
    }
  })
  if (!user) {
    return res.status(404).json({
      code: 404,
      msg: '未找到授权用户'
    })
  } else if (user) {
    user = user.get({
      plain: true
    })
    if (user.passwd !== Tool.encrypt(req.body.passwd)) {
      return res.status(401).json({
        code: 401,
        msg: '用户密码错误'
      })
    } else if (user.isActive === 0) {
      return res.status(401).json({
        code: 401,
        msg: '用户没有被激活'
      })
    } else {
      var token = jwt.sign(user, config.jwt.secret, {
        expiresIn: 60 * 60 * 24 // 授权时效24小时
      })
      let retUser = {
        loginName: user.loginName,
        userName: user.userName,
        avatar: user.avatar ? user.avatar : ''
      }
      return res.json({
        code: 0,
        msg: '请使用您的授权码',
        user: retUser,
        token: token
      })
    }
  }
})

module.exports = router
